package com.xu.t1.mapper;

import com.xu.t1.model.UploadLog;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

/**
 * 负责操作写入状态记录数据的持久化接口类
 *
 * @author xu
 *
 */

@Mapper
public interface UploadLogMapper {

    @Insert("""
        INSERT INTO upload_log (
            log_id,
            timestamp,
            server_id,
            instruction_id,
            user_id,
            thread_count,
            duration_ms,
            distributed_lock,
            optimistic_lock,
            message
        ) VALUES (
            #{log.logId},
            #{log.timestamp},
            #{log.serverId},
            #{log.instructionId},
            #{log.userId},
            #{log.threadCount},
            #{log.durationMs},
            #{log.distributedLockJson},
            #{log.optimisticLockJson},
            #{log.message}
        )
    """)
    int insertUploadLog(@Param("log") UploadLog log);

    // 查询近期平均单位人数使用线程数
    @Select("""
            SELECT IFNULL(AVG(thread_count), 0) AS avgThreadCount
                    FROM (
                        SELECT thread_count
                        FROM upload_log
                        WHERE server_id = #{serverId}
                        ORDER BY timestamp DESC
                        LIMIT 30
                    ) AS recent_logs
            """)
    Double avgThreadCont(@Param("serverId") String serverId);

    // 查询近期平均单位人数单次任务执行平均时间
    @Select("""
            SELECT IFNULL(AVG(duration_ms), 0) AS avgDuration_ms
                    FROM (
                        SELECT duration_ms
                        FROM upload_log
                        WHERE server_id = #{serverId}
                        ORDER BY timestamp DESC
                        LIMIT 30
                    ) AS recent_logs
            """)
    Double avgDurationMs(@Param("serverId") String serverId);
}